package com.sy.core.util;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Cookie工具类
 *
 * @Author :Chong.CaiXin
 * @Description :
 * @Date : Created in 16:37 2018/9/19
 */
public class CookUtils {

    /**
     * 获取请求的用户ID
     *
     * @param request
     * @return
     */
    public String getLoginUserId(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("SYSTEMUSERID")) {
                    return cookies[i].getValue();
                }
            }
        }
        return null;
    }

    /**
     * 生产Cookie
     *
     * @param userId
     * @return
     */
    public  Cookie productCookie(String userId) {
        Cookie coo = new Cookie("SYSTEMUSERID", userId);
        coo.setPath("/");
        coo.setMaxAge(365 * 24 * 60 * 60);
        return coo;
    }

    /**
     * 销毁Cookie
     * @param response
     */
    public void destoryCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("Authorization", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 拆分大集合集合
     * @param <T>
     * @param resList  要拆分的集合
     * @param count    每个集合的元素个数
     * @return  返回拆分后的各个集合
     */
    public static  <T> List<List<T>> split(List<T> resList,int count){

        if(resList==null ||count<1)
            return  null ;
        List<List<T>> ret=new ArrayList<List<T>>();
        int size=resList.size();
        if(size<=count){ //数据量不足count指定的大小
            ret.add(resList);
        }else{
            int pre=size/count;
            int last=size%count;
            //前面pre个集合，每个大小都是count个元素
            for(int i=0;i<pre;i++){
                List<T> itemList=new ArrayList<T>();
                for(int j=0;j<count;j++){
                    itemList.add(resList.get(i*count+j));
                }
                ret.add(itemList);
            }
            //last的进行处理
            if(last>0){
                List<T> itemList=new ArrayList<T>();
                for(int i=0;i<last;i++){
                    itemList.add(resList.get(pre*count+i));
                }
                ret.add(itemList);
            }
        }
        return ret;

    }
}
